package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.constants.CashRecordConstants;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserBill;
import com.zbkj.common.model.user.UserCashRecord;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.AdminCashSearchRequest;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.response.UserCashRecordResponse;
import com.zbkj.common.utils.DateUtil;
import com.zbkj.common.vo.dateLimitUtilVo;
import com.zbkj.service.dao.UserCashRecordDao;
import com.zbkj.service.service.UserCashRecordService;
import com.zbkj.service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户礼金记录 服务层实现
 *
 * @author Swallows
 * @date 2022-09-26 10:54
 */
@Slf4j
@Service
public class UserCashRecordServiceImpl extends ServiceImpl<UserCashRecordDao, UserCashRecord> implements UserCashRecordService {

    @Resource
    private UserCashRecordDao userCashRecordDao;
    @Autowired
    private UserService userService;

    @Override
    public void cashThaw() {

    }

    @Override
    public List<UserCashRecord> findListByOrderIdAndUid(String orderNo, Integer uid) {

        LambdaQueryWrapper<UserCashRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(UserCashRecord::getUid, uid);
        lqw.eq(UserCashRecord::getLinkId, orderNo);
        lqw.in(UserCashRecord::getStatus, CashRecordConstants.CASH_RECORD_STATUS_CREATE, CashRecordConstants.CASH_RECORD_STATUS_FROZEN, CashRecordConstants.CASH_RECORD_STATUS_COMPLETE);
        List<UserCashRecord> recordList = userCashRecordDao.selectList(lqw);
        if (CollUtil.isEmpty(recordList)) {
            return recordList;
        }
        for (int i = 0; i < recordList.size();) {
            UserCashRecord record = recordList.get(i);
            if (record.getType().equals(CashRecordConstants.CASH_RECORD_TYPE_ADD)) {
                if (record.getStatus().equals(CashRecordConstants.CASH_RECORD_STATUS_COMPLETE)) {
                    recordList.remove(i);
                    continue;
                }
            }
            i++;
        }
        return recordList;
    }

    @Override
    public List<UserCashRecord> findUserCashRecordList(String type, Integer uid, PageParamRequest pageParamRequest) {

        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<UserCashRecord> lqw = Wrappers.lambdaQuery();
        lqw.select(UserCashRecord::getId, UserCashRecord::getTitle, UserCashRecord::getType, UserCashRecord::getCash, UserCashRecord::getUpdateTime);
        lqw.eq(UserCashRecord::getUid, uid);
        lqw.eq(UserCashRecord::getStatus, CashRecordConstants.CASH_RECORD_STATUS_COMPLETE);
        switch (type) {
            case "all":
                break;
            case "expenditure":
                lqw.eq(UserCashRecord::getType, 2);
                break;
            case "income":
                lqw.eq(UserCashRecord::getType, 1);
                break;
        }
        lqw.orderByDesc(UserCashRecord::getUpdateTime);
        return userCashRecordDao.selectList(lqw);
    }

    @Override
    public Integer getSumCash(Integer uid, Integer type, String date, String linkType) {

        QueryWrapper<UserCashRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sum(cash) as cash");
        queryWrapper.eq("uid", uid);
        queryWrapper.eq("type", type);
        if (StrUtil.isNotBlank(linkType)) {
            queryWrapper.eq("link_type", linkType);
        }
        queryWrapper.eq("status", CashRecordConstants.CASH_RECORD_STATUS_COMPLETE);
        if (StrUtil.isNotBlank(date)) {
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(date);
            queryWrapper.between("update_time", dateLimit.getStartTime(), dateLimit.getEndTime());
        }
        UserCashRecord cashRecord = userCashRecordDao.selectOne(queryWrapper);
        if (ObjectUtil.isNull(cashRecord) || ObjectUtil.isNull(cashRecord.getCash())) {
            return 0;
        }
        return cashRecord.getCash();
    }

    @Override
    public PageInfo<UserCashRecordResponse> findAdminList(AdminCashSearchRequest request, PageParamRequest pageParamRequest) {

        Page<UserCashRecordResponse> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<UserCashRecord> lqw = Wrappers.lambdaQuery();
        lqw.select(UserCashRecord::getId, UserCashRecord::getTitle, UserCashRecord::getBalance, UserCashRecord::getCash,
                UserCashRecord::getMark, UserCashRecord::getUid, UserCashRecord::getUpdateTime);
        lqw.eq(UserCashRecord::getStatus, CashRecordConstants.CASH_RECORD_STATUS_COMPLETE);
        if (ObjectUtil.isNotNull(request.getUid())) {
            lqw.eq(UserCashRecord::getUid, request.getUid());
        }
        if (StrUtil.isNotBlank(request.getKeywords())) {
            List<Integer> idList = userService.findIdListLikeName(request.getKeywords());
            if (CollUtil.isNotEmpty(idList)) {
                lqw.in(UserCashRecord::getUid, idList);
            } else {
                return CommonPage.copyPageInfo(page, CollUtil.newArrayList());
            }
        }
        //时间范围
        if (StrUtil.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());
            //判断时间
            int compareDateResult = DateUtil.compareDate(dateLimit.getEndTime(), dateLimit.getStartTime(), Constants.DATE_FORMAT);
            if (compareDateResult == -1) {
                throw new CrmebException("开始时间不能大于结束时间！");
            }

            lqw.between(UserCashRecord::getUpdateTime, dateLimit.getStartTime(), dateLimit.getEndTime());
        }
        lqw.orderByDesc(UserCashRecord::getUpdateTime);
        List<UserCashRecord> list = userCashRecordDao.selectList(lqw);
        if (CollUtil.isEmpty(list)) {
            return CommonPage.copyPageInfo(page, CollUtil.newArrayList());
        }
        List<UserCashRecordResponse> responseList = list.stream().map(i -> {
            UserCashRecordResponse response = new UserCashRecordResponse();
            BeanUtils.copyProperties(i, response);
            // 获取用户昵称
            User user = userService.getById(i.getUid());
            if (ObjectUtil.isNotNull(user)) {
                response.setNickName(user.getNickname());
            } else {
                response.setNickName("");
            }
            return response;
        }).collect(Collectors.toList());
        return CommonPage.copyPageInfo(page, responseList);
    }
}
